package com.agentframework.examples.jinhua;

import com.agentframework.core.agent.Agent;
import com.agentframework.core.annotation.Action;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.Set;

import static com.agentframework.core.agent.Agent.VIEW_TO;

/**
 * 处理玩家弃牌动作
 * @author wangjun
 */
@Action(name = "fold")
public class FoldAction extends JinhuaDealerAction {
    
    public FoldAction(JinhuaTool jinhuaTool) {
        super("fold", jinhuaTool);
    }
    
    @Override
    protected String getFormatInstruction() {
        return """
            你需要处理玩家的弃牌请求，请必须且只能返回如下JSON格式：
            {
                "playerId": "玩家ID",
                "message": "确认玩家弃牌的消息",
                "nextPlayerId": "下一个玩家"
            }
            
            错误返回：
            由于玩家已弃牌，本次弃牌失败 {
                "playerId": "0d8f6620",
                "betAmount": "10",
                "message": "玩家0d8f6620看牌后下注10",
                "betStatus": "1",
                "nextPlayerId": "4bea25a3"
            }
            
            正确示范：
            {
                "playerId": "玩家ID（例如：e9fc1d4d）",
                "message": "由于玩家已弃牌，本次弃牌失败，玩家player-1已选择弃牌",
                "nextPlayerId": "下一个玩家ID（例如：e9fc2db4d）"
            }
            
            请使用fold工具处理玩家弃牌，参数为玩家ID
            """;
    }

    @Override
    protected void doHandleResponseMessage(Message message, Object response) {
        var foldResp = (FoldResp) response;

        String playerId = foldResp.playerId();
        String messageContent = foldResp.message();
        String nextPlayerId = foldResp.nextPlayerId();

        // 通知玩家弃牌成功
//        Message foldMessage = new UserMessage(messageContent);
//        foldMessage.getMetadata().put(Agent.MSG_FROM, agent.getAgentId());
//        foldMessage.getMetadata().put(Agent.SEND_TO, Set.of(playerId));
//        env.publishMessage(foldMessage);

        // 广播弃牌信息给所有玩家
        Message broadcastMessage = new UserMessage(String.format("玩家%s已弃牌", playerId));
        broadcastMessage.getMetadata().put(Agent.SEND_TO, getPlayerIds());
        broadcastMessage.getMetadata().put(VIEW_TO, getPlayerIds());
        publishMessage(broadcastMessage);

        logger.debug("玩家{}已弃牌", playerId);

        // 通知下一个玩家行动
        Message nextMessage = new UserMessage(messageContent);
        nextMessage.getMetadata().put(Agent.SEND_TO, Set.of(nextPlayerId));
        publishMessage(nextMessage);
    }

    @Override
    protected Class<?> getResponseType() {
        return FoldResp.class;
    }

    record FoldResp(String playerId, String message, String nextPlayerId) {

    }

} 